﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using IOP.SgrA.Input;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace VkSample65
{
    public class TransformSystem : ComponentSystem
    {
        private float AngleX;
        private float AngleY;
        const float SPAN = 10;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="contextManager"></param>
        public TransformSystem()
        {
        }

        public override void Initialization()
        {
            float currLodLevel = -1;
            float startx = -SPAN;
            float startY = SPAN;
            int i = 0;
            int j = 0;
            ContextManager.Foreach<Group>((group) =>
            {
                currLodLevel++;
                Context context = ContextManager.GetContext(group.Entity);
                context.SetCustomPropery("level", currLodLevel);
                group.Transform.Position = new Vector3(startx + SPAN * j, startY - i * SPAN, 0);
                j++;
                if(j > 2)
                {
                    j = 0;
                    i++;
                }
                return group;
            });
        }

        public override void Update(TimeSpan timeSpan)
        {
            float diffX = 0;
            float diffY = 0;
            if (Input.GetMouseButtonState(MouseButton.ButtonLeft).Action == InputAction.Press)
            {
                Vector2 p = Input.GetMousePositionDelta();
                diffX = p.X;
                diffY = p.Y;
            }
            AngleX += diffX * 180 / 200;
            AngleY += diffY * 180 / 200;
            ContextManager.Foreach<Group>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                ref MVPMatrix mvp = ref context.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateRotationY(AngleX / 180.0f * MathF.PI) *
                Matrix4x4.CreateRotationZ(AngleY / 180.0f * MathF.PI) * Matrix4x4.CreateTranslation(group.Transform.Position);
                context.PushToRenderGroup();
            });
        }

        public struct Group
        {
            public Entity Entity;
            public TransformComponent Transform;
        }
    }
}
